/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.dusin.adserver.servlet.charts;

import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dusin.adserver.db.dao.GerneralDao;
import org.dusin.adserver.utils.TheUtil;
import org.dusin.util.DateUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 *
 * @author dusin
 */
@WebServlet(name = "GetChartsData", urlPatterns = {"/servlet/charts/GetChartsData"})
public class GetChartsData extends HttpServlet {

    GerneralDao instance = null;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            //BigDecimal.setScale(1,BigDecimal.ROUND_HALF_UP);
            ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
            instance = (GerneralDao) context.getBean("gerneralDaoProxy");

            String startYearMonth = request.getParameter("startYearMonth");
            String endYearMonth = request.getParameter("endYearMonth");
            
            
            
            String[] models = request.getParameterValues("models[]");
            String[] companies = request.getParameterValues("companies[]");
            String now = DateUtil.get(new Date(), "yyyyMM");
            
            if (endYearMonth == null || "".equals(endYearMonth.trim())) {
                endYearMonth = now;
            }
            //起始日期默认当月
            if (startYearMonth == null || "".equals(startYearMonth.trim())) {
                startYearMonth = now;
            }
            List<String> yearMonthList = DateUtil.getYearMonthList(startYearMonth, endYearMonth);
            
            List<Map<String, Object>> list = instance.findAllProfit(startYearMonth, endYearMonth, null, null);
            List<Map<String, Object>> list2 = instance.findAllProfitSum4ModelPie(startYearMonth, endYearMonth, models, null);
            List<Map<String, Object>> listGp3 = instance.findSum4GP3Each(startYearMonth, endYearMonth, models, companies);
            List<Map<String, Object>> listMaoli = instance.findSum4MLEach(startYearMonth, endYearMonth, models, companies);
            List<Map<String, Object>> listGoWhere = instance.findSum4GoWhere(startYearMonth, endYearMonth, models, companies);

            List<Map<String, Object>> listGp3Trend = instance.findAll4GP3EachTrend(startYearMonth, endYearMonth, models, companies);
            List<Map<String, Object>> listMaoliTrend = instance.findAll4MaoliEachTrend(startYearMonth, endYearMonth, models, companies);
            List<Map<String, Object>> listVolumnTrend = instance.findAll4VolumeTrend(startYearMonth, endYearMonth, models, companies);

            List<String> companyNames = new ArrayList<String>();
            List<BigDecimal> gp3 = new ArrayList<BigDecimal>();

            for (Map<String, Object> m : listGp3) {
                companyNames.add((String) m.get("name"));
                gp3.add((BigDecimal) m.get("value"));
            }

            List<BigDecimal> maoli = new ArrayList<BigDecimal>();
            for (Map<String, Object> m : listMaoli) {
                maoli.add((BigDecimal) m.get("value"));
            }

            
            
            Map<String,Object> mapVolumne= TheUtil.storesTrend4Integer("Volumn", yearMonthList, listVolumnTrend);
            Map<String,Object> mapMaoli = TheUtil.storesTrend4BigDecimal("avg","Maoli", yearMonthList, listMaoliTrend);
            Map<String,Object> mapGp3 = TheUtil.storesTrend4BigDecimal("avg","Gp3", yearMonthList, listGp3Trend);

            List<Map<String, Object>> goWhere = new ArrayList<Map<String, Object>>();
            String[] dqNames = new String[]{"镇江市区", "丹阳", "扬中", "句容", "省内外市", "省外"};
            String[] dqFields = new String[]{"zjsq", "dy", "yz", "jr", "sn", "sw"};
            if (listGoWhere != null && listGoWhere.size() > 0) {
                Map<String, Object> m = listGoWhere.get(0);

                for (int i = 0; i < dqNames.length; i++) {
                    Map<String, Object> dqMap = new HashMap<String, Object>();
                    dqMap.put("name", dqNames[i]);
                    dqMap.put("value", m.get(dqFields[i]));
                    goWhere.add(dqMap);
                }
            }

            Gson gson = new Gson();
            Map map = new HashMap<String, Object>();
            map.put("dqxl", list);
            map.put("modelPie", list2);
            map.put("companyNames", companyNames);
            map.put("gp3", gp3);
            map.put("maoli", maoli);
            map.put("goWhere", goWhere);
            map.put("yearMonth", yearMonthList);

            map.putAll(mapVolumne);
            map.putAll(mapMaoli);
            map.putAll(mapGp3);
            
            String jsonText = gson.toJson(map);

            out.println(jsonText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
